import axios, { type Method } from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { ElMessage } from 'element-plus'

//创建请求实例
const mockAxios = axios.create({
    baseURL:'/sph',
    timeout:5000
})

//请求拦截器
mockAxios.interceptors.request.use((config)=>{
    //展示进度条
    NProgress.start()

    return config
})

//响应拦截器
mockAxios.interceptors.response.use((response)=>{
    //关闭进度条
    NProgress.done()
    //简化数据，返回服务器响应的真正结果
    const res = response.data
    return res
},(error)=>{
    //提示
    ElMessage.error('请求失败')
    return Promise.reject(error || 'error')
})

export interface IResponseData<T> {
    code: number
    message: string
    success?: boolean
    data: T
    ok?:boolean
  }

//封装请求方法request
function httpMock<T>(url: string, method: Method, submitData?: any): Promise<IResponseData<T>> {
    //将传递的请求方式进行大写转换
    const newMethod = method.toUpperCase()
    //判断请求的方式：如果请求方式为post、delete、put，请求数据为data；如果请求方式为get，请求数据为params
    const data =
      newMethod === 'POST' || newMethod === 'PUT' || newMethod === 'DELETE' ? submitData : {}
    const params = newMethod === 'GET' ? submitData : {}
  
    return mockAxios.request({
      url,
      method,
      data,
      params
    })
  }

//暴露
export {mockAxios,httpMock}